package com.yilin.tms.order.service.owner.impl;

import com.yilin.commons.exception.BusinessException;
import com.yilin.commons.util.CommonUtil;
import com.yilin.commons.util.StringUtil;
import com.yilin.tms.core.commons.model.AuthStatus;
import com.yilin.tms.core.commons.utils.ParamUtil;
import com.yilin.tms.core.entity.order.payment.OrderPaymentCost;
import com.yilin.tms.core.entity.order.rob.RobOrder;
import com.yilin.tms.core.entity.truck.TravelLicense;
import com.yilin.tms.core.entity.truck.TruckVehicle;
import com.yilin.tms.core.entity.user.UserType;
import com.yilin.tms.core.entity.user.account.Account;
import com.yilin.tms.core.entity.user.auth.DrivingLicense;
import com.yilin.tms.core.entity.user.auth.IdCard;
import com.yilin.tms.core.entity.user.auth.QualificationCert;
import com.yilin.tms.core.entity.user.organize.MemberType;
import com.yilin.tms.order.service.owner.IRobOwnerService;
import com.yilin.tms.order.service.order.IRobService;
import com.yilin.tms.order.service.payment.IOrderPaymentCostService;
import com.yilin.tms.core.remote.IUserRemote;
import com.yilin.tms.core.remote.IVehicleRemote;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;

/**
 * 抢单前台操作标识
 *
 * @author zhangjinyuan
 * @date 2022/10/29
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class RobOwnerService implements IRobOwnerService {

    @Resource
    IRobService robService;
    @Resource
    IOrderPaymentCostService paymentCostService;

    @Resource
    IUserRemote userRemote;
    @Resource
    IVehicleRemote vehicleRemote;

    /**
     * 获取前台操作标识
     */
    @Override
    public void getCanOperationMark(Account loginUser, RobOrder robOrder,OrderPaymentCost robPayment) {
        //是否是我的抢单
        boolean ownerShipper = loginUser.getId().equals(robOrder.getShipperAccountId());
        boolean ownerTrucker = loginUser.getId().equals(robOrder.getRobAccountId());
        robOrder.setOwner(ownerShipper || ownerTrucker);
        //货主是否已支付 公共
        robOrder.setShipperPay(getShipperPay(robPayment));
        //是否可以支付 货主
        robOrder.setShipperCanPay(ownerShipper && getShipperCanPay(robOrder));
        //是否可审核抢单  货主
        robOrder.setShipperCanCheck(ownerShipper && getShipperCanCheck(robOrder));
        //是否能分配车辆  車主
        robOrder.setTruckerCanAssign(ownerTrucker && getTruckerCanAssign(robOrder));
        //是否能取消抢单  車主
        robOrder.setTruckerCanCancel(ownerTrucker && getTruckerCanCancel(loginUser, robOrder));
        //操作提示 公共
        robOrder.setOptTip(getOptTip(loginUser, robOrder));
    }

    /**
     * 检查司机基本信息认证是否完善
     */
    @Override
    public void checkTruckUserBaseData(TruckVehicle truckVehicle) {
        Account truckUser = ParamUtil.isSuccess(userRemote.getAccountById(truckVehicle.getTruckUserId()));
        //身份证
        IdCard idCard = ParamUtil.isSuccess(userRemote.getIdCardByUserId(truckUser.getId()));
        if (idCard == null || idCard.getAuthStatus() != AuthStatus.authSuccess) {
            throw new BusinessException("请先完成身份证认证");
        }
        //驾驶证
        DrivingLicense drivingLicense = ParamUtil.isSuccess(userRemote.getDrivingLicenseByUserId(truckUser.getId()));
        if (drivingLicense == null || drivingLicense.getAuthStatus() != AuthStatus.authSuccess) {
            throw new BusinessException("请先完成驾驶证认证");
        }
        //行驶证
        TravelLicense travelLicense = ParamUtil.isSuccess(vehicleRemote.getTravelLicenseByVehicleId(truckVehicle.getId()));
        if (travelLicense == null || travelLicense.getAuthStatus() != AuthStatus.authSuccess) {
            throw new BusinessException("请先完成行驶证认证");
        }
        if (truckVehicle.getVehicleWeight() > 4.5) {
            //从业资格证
            QualificationCert qualificationCert = ParamUtil.isSuccess(
                    userRemote.getQualificationCertByUserId(truckUser.getId()));
            if (qualificationCert == null || qualificationCert.getAuthStatus() != AuthStatus.authSuccess) {
                throw new BusinessException("请先完成从业资格证认证");
            }
        }
    }

    /**
     * 隐藏抢单敏感信息
     */
    @Override
    public void robOrderPrivateData(RobOrder robOrder) {
        //隐藏货主名
        if (StringUtil.isNotEmpty(robOrder.getShipperAccountName())) {
            robOrder.setShipperAccountName(StringUtil.privateName(robOrder.getShipperAccountName()));
        }
        if (StringUtil.isNotEmpty(robOrder.getShipperOrganizeName())) {
            robOrder.setShipperOrganizeName(StringUtil.privateName(robOrder.getShipperOrganizeName()));
        }
        //货主电话
        if (StringUtil.isNotEmpty(robOrder.getShipperAccountPhone())) {
            robOrder.setShipperAccountPhone(StringUtil.privatePhone(robOrder.getShipperAccountPhone()));
        }
        //车主名
        if (StringUtil.isNotEmpty(robOrder.getRobAccountName())) {
            robOrder.setRobAccountName(StringUtil.privateName(robOrder.getRobAccountName()));
        }
        if (StringUtil.isNotEmpty(robOrder.getRobOrganizeName())) {
            robOrder.setRobOrganizeName(StringUtil.privateName(robOrder.getRobOrganizeName()));
        }
        //车主电话
        if (StringUtil.isNotEmpty(robOrder.getRobAccountPhone())) {
            robOrder.setRobAccountPhone(StringUtil.privatePhone(robOrder.getRobAccountPhone()));
        }
    }

    /**
     * 获取抢单详情链接
     * 例：http://127.0.0.1:8082/logistics/goods/getGoodsOrderViewDetail.do?goodsOrderId=123
     */
    @Override
    public String getRobOrderDetailUrl(String robOrderId) {
        return CommonUtil.getUrl() + "/logistics/rob/getPublicRobOrderDetail.do?robOrderId=" + robOrderId;
    }

    /**
     * 检查收发货地址节点
     */
    @Override
    public void checkReceiveAndDeliverNote(RobOrder robOrder) {
        if (robOrder.getRobOrderNoteList().size() >= 50) {
            throw new BusinessException("抢单节点过多，暂时不能超过50个");
        }
    }

    /**
     * 操作提示
     */
    private String getOptTip(Account loginUser, RobOrder robOrder) {
        if (loginUser.getUserType() == UserType.shipperUser) {
            if (robOrder.getShipperCanPay()) return "审核成功，请尽快完成付款，付款后司机才能派车";
            if (!robOrder.getOwner()){
                robOrderPrivateData(robOrder);
                return "正在浏览他人抢单，如需帮助，请仔细阅读“帮助文档";
            }
            return robOrder.getRobStatus().shipperTip;
        }
        if (loginUser.getUserType() == UserType.truckerUser) {
            if (!robOrder.getShipperPay()) return "抢单已审核成功，请等待货主完成付款";
            if (!robOrder.getOwner()){
                robOrderPrivateData(robOrder);
                return "正在浏览他人抢单，如需抢单帮助，请仔细阅读“帮助文档";
            }
            return robOrder.getRobStatus().truckerTip;
        }
        return "浏览中，登录货主/车主查看更多详情";
    }

    /**
     * 货主 是否已支付
     */
    private boolean getShipperPay(OrderPaymentCost robPayment) {
        if (robPayment == null) return false;
        if (robPayment.getPayStatus() == OrderPaymentCost.PayStatus.none) return true;
        return robPayment.getPayStatus() == OrderPaymentCost.PayStatus.complete;
    }

    /**
     * 货主 是否可以支付
     */
    private boolean getShipperCanPay(RobOrder robOrder) {
        if (robOrder.getRobStatus() != RobOrder.RobStatus.success) return false;
        return !robOrder.getShipperPay();
    }

    /**
     * 货主 是否可审核抢单
     */
    private boolean getShipperCanCheck(RobOrder robOrder) {
        //支付在审核成功后
        return robOrder.getRobStatus() == RobOrder.RobStatus.wait;
    }

    /**
     * 车主 是否能分配车辆
     */
    private boolean getTruckerCanAssign(RobOrder robOrder) {
        if (robOrder.getRobStatus() != RobOrder.RobStatus.success) return false;
        return robOrder.getShipperPay();
    }

    /**
     * 车主 是否能取消抢单
     */
    @Override
    public boolean getTruckerCanCancel(Account loginUser, RobOrder robOrder) {
        if (loginUser.getUserType() != UserType.truckerUser) return false;
        if (!robOrder.getOwner()) return false;
        if (robOrder.getRobStatus() != RobOrder.RobStatus.success) return false;
        int number = robService.getCancelNumberByUser(loginUser);
        MemberType memberType = ParamUtil.isSuccess(userRemote.getMyMemberTypeByOrganizeId(loginUser.getOrganizeId()));
        return number <= memberType.getCancelRobCount();
    }
}